var app = getApp()
import ajaxhelper from '../../utils/ajaxhelper.js';
// import { signByMd5 } from "../../utils/util";
// import { CryptoJSFun } from "../../utils/tripledes.js";
// var CryptoJSFun = require("../../utils/tripledes.js");
// var decypt = require("../../utils/decrypt.js");
import checkLogin from '../../utils/checkLogin.js';
var goCommentPop = require("../common/goCommment/goCommment.js");//评论
var payBtn = require('../common/payBtn/payBtn.js');
Page(Object.assign({}, payBtn,{
  data: {
    isplay:false,
    currentTab: 1, //预设当前项的值
    isMoreIntro: false,
    canPlay:false,//是否可以播放
    totalPrice:'',//购买价格
    canView: true,//默认可以观看
  },
  onLoad: function (options) {
    var that= this;
    var isFromShare = options.isFromShare||'';//是否是分享过来的
    var urlObj = options.urlObj||"{}";
    urlObj = JSON.parse(urlObj);
    that.setData({
      urlObj
    })
    console.log(urlObj)
    //播放控制
    var playUrl = urlObj.url || '';
    that.setData({
      // playUrl: playUrl,
      cover: urlObj.cover||'',
      curPlayIndex: urlObj.index,//正在播放的序号
      courseId: urlObj.courseId,//课程id
      isFromShare,
      // canPlay: true
    })
    this.videoContext = wx.createVideoContext('myVideo');
    that.getNetworkType(function (){
      that.setData({
        playUrl: playUrl,
      })
      that.play();
    });
    // that.play();
  },
  onShow(){
    // 检查有没有登录，第二个参数是回调函数
    checkLogin.login(this, function (res) {
      console.log(res)
      this.getAllDetail();//获取详情页面数据
    })
  },
  onReady: function (res) {
  },
  getAllDetail() {
    var id = this.data.courseId;
    var token = (wx.getStorageSync('Token_date') && wx.getStorageSync('Token_date').Token) || '';
    ajaxhelper.get(app.globalData.frontJSHost + 'knowledge/detailById/' + id + '?token=' + encodeURIComponent(token), {}, this, this.setAllDetail)

  },
  setAllDetail(res) {
    var that = this;
    if (res.result) {
      var indexList = res.data.indexList;
      if (indexList) {
        // 处理时间
        var resourcesList = []; //吧所有课程放到一个数组里面
        indexList.forEach(function (item, index, arr) {
          if (item.resources && item.resources.length > 0) {
            item.resources.forEach(function (itemRe, index, arr) {
              itemRe.volume = app.timeFormat(itemRe.length);
              itemRe.createDate = new Date(+itemRe.createDate).format("yyyy-MM-dd hh:mm");
              resourcesList.push(itemRe);
            })
          }
        })
        res.data.resourcesList = resourcesList;
      }
      if (res.data.updateDate) {
        res.data.updateDate = new Date(+res.data.updateDate).format("yyyy年MM月dd日");
      }
      if (res.data.statistics) {
        res.data.statistics.avgPoint = res.data.statistics.avgPoint && res.data.statistics.avgPoint.toFixed(1);///保留一位小数
      }
      that.setData({
        lecturers: res.data.lecturers,//讲师
        course: res.data.course,//视频简介介绍
        indexList: res.data.indexList,//视频列表
        statistics: res.data.statistics,//评分评论
        subject: res.data.subject,//分类
        canView: res.data.canView,//是否可以播放
        resourcesList: res.data.resourcesList,//处理好的视频列表
        favoriteCount: res.data.favoriteCount,//订阅的个数
        isSubscribe: res.data.favoriteStatus,//是否订阅
        chapterCount: res.data.chapterCount,//总共集数
        updateDate: res.data.updateDate,//更新日期
        totalPrice: res.data.course.currentPrice,//购买价格
      })
      if (that.data.isFromShare){
        //分享过来的 根据请求回来的canview来觉得取哪个url
        // (that.data.canView || (!that.data.canView && that.data.resourcesList[0].snapshotFlag)) ? that.data.resourcesList[0].url : ''
        // that.setData({
        //   playUrl: (that.data.canView || (!that.data.canView && that.data.resourcesList[0].snapshotFlag)) ? that.data.resourcesList[0].url : '',
        // })
        that.getNetworkType(function () {
          that.setData({
            playUrl: (that.data.canView || (!that.data.canView && that.data.resourcesList[0].snapshotFlag)) ? that.data.resourcesList[0].url : '',
          })
          that.play();
        });
      }
    } else {
      wx.showToast({
        title: !!res.message.global ? res.message.global : "请求出错",
        icon: "loading"
      })
    }
    // that.play();
  },
  // 从内存中获取存储的视频信息
  // setAllDetail() {
  //   var that = this;
  //   wx.getStorage({
  //     key: 'allVideoDetail',
  //     success: function(res) {
  //       if(res.data){
  //         var result = JSON.parse(res.data);
  //         that.setData({
  //           lecturers: result.lecturers,//讲师
  //           course: result.course,//视频简介介绍
  //           indexList: result.indexList,//视频列表
  //           statistics: result.statistics,//评分评论
  //           subject: result.subject,//分类
  //           canView: result.canView,//是否可以播放
  //           resourcesList: result.resourcesList,//处理好的视频列表
  //           favoriteCount: result.favoriteCount,//订阅的个数
  //           isSubscribe: result.favoriteStatus,//是否订阅
  //           chapterCount: result.chapterCount,//总共集数
  //           updateDate: result.updateDate,//更新日期
  //           totalPrice: result.course.currentPrice
  //         })
  //         console.log(result)
          
  //       }
  //       that.play();//播放
  //     },
  //   })
  // },
  // 播放
  play: function () {
    var that = this;
    var videoContext = that.videoContext;
    var backgroundAudioManager = app.backgroundAudioManager;
    if (backgroundAudioManager.src){
      backgroundAudioManager.pause();
    }
    that.setData({
      isPlay: false
    })
    if (!that.data.canView && !that.data.playUrl) {
      wx.showToast({
        title: '请购买视听',
        icon: 'loading'
      })
      return false;
    }
    if (that.data.canView && !that.data.playUrl) {
      wx.showToast({
        title: '资源地址有误，请确认',
        icon: 'loading'
      })
      return false;
    }
    
    that.setData({
      isPlay: true
    })
    videoContext.play();
  },
  // 暂停播放
  pauseVideo() {
    var that=this;
    var videoContext = that.videoContext;
    that.setData({
      isPlay: false
    })
    videoContext.pause();
  },
  // 继续播放
  playVideo() {
    var that = this;
    var videoContext = that.videoContext;
    that.setData({
      isPlay: true
    })
    videoContext.play();
  },
  // 播放下一首
  playNext() {
    var that = this;
    that.setData({
      isPlay: false
    })
    if (that.data.curPlayIndex == that.data.resourcesList.length - 1) {
      wx.showToast({
        title: '播完喽',
        icon: 'loading'
      })
    } else {
      // 获取下一首的地址
      // 判断是否为试听试看
      var curPlayIndex = that.data.curPlayIndex + 1;
      var resourcesItem = that.data.resourcesList[curPlayIndex];
      var url = (that.data.canView || (!that.data.canView && resourcesItem.snapshotFlag)) ? resourcesItem.url : '';///////////视频地址是试听地址还是正式地址
      //var url = that.data.canView ? resourcesItem.url : resourcesItem.snapshotUrl;///////////视频地址是试听地址还是正式地址
      var id = resourcesItem.id;//课程中资源id
      var courseId = resourcesItem.courseId;//课程id
      var index = curPlayIndex;//课程序号
      var cover = resourcesItem.cover;
      // var obj = {
      //   url,
      //   id,
      //   courseId,
      //   index
      // }
      // // 存储要播放的urlobj
      // wx.setStorage({
      //   key: 'gloalObjUrl',
      //   data: JSON.stringify(obj),
      // })
      that.setData({
        curPlayIndex: curPlayIndex,
        // playUrl: url,
        cover:cover,
      })
      that.getNetworkType(function () {
        that.setData({
          playUrl: url,
        })
        that.play();
      });
      // that.play()//调用播放
      //播放统计
      app.addHit(id, 'RESOURCE_VIDEO');
    }
  },
  // 点击播放的图片控制播放
  controlPlayItem(e) {
    var that = this;
    var playUrl = that.data.playUrl;
    var curPlayIndex = that.data.curPlayIndex;
    // if (this.data.canView){
    var url = e.currentTarget.dataset.url;
    var id = e.currentTarget.dataset.resourceId;//课程中资源id
    var courseId = e.currentTarget.dataset.courseId;//课程id
    var index = e.currentTarget.dataset.index;//课程序号
    var cover = e.currentTarget.dataset.cover;//资源封面
    var obj = {
      url,
      id,
      courseId,
      index,
      cover
    }
   
    // // 存储要播放的urlobj
    // wx.setStorage({
    //   key: 'gloalObjUrl',
    //   data: JSON.stringify(obj),
    // })
    if (curPlayIndex == index){
      if (that.data.isPlay) {
        that.pauseVideo();
      } else {
        that.playVideo()
      }
    }else{
      if (!that.data.canView && !url) {
        // wx.showToast({
        //   title: '请购买视听',
        //   icon: 'loading'
        // })
        //改为弹窗购买链接
        wx.showModal({
          title: '提示',
          content: '请购买该资源',
          confirmColor: '#FF4612',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定');
              that.goPay();//购买
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
        return false;
      }
      if (that.data.canView && !url) {
        wx.showToast({
          title: '资源地址有误，请确认',
          icon: 'loading'
        })
        return false;
      }
      that.setData({
        urlObj: obj,
        currentPlayId: id,
        playUrl: url,
        curPlayIndex: index,
        cover:cover,
      })
      that.play()
    }
  },
  // 切换视频播放地址
  changePlayUrl(e){
    var that = this;
    var url = e.currentTarget.dataset.url;
    var id = e.currentTarget.dataset.resourceId;//课程中资源id
    var courseId = e.currentTarget.dataset.courseId;//课程id
    var index = e.currentTarget.dataset.index;//课程序号
    var cover = e.currentTarget.dataset.cover;//资源封面
    var obj = {
      url,
      id,
      courseId,
      index,
      cover
    }
    if (!that.data.canView && !url) {
      // wx.showToast({
      //   title: '请购买视听',
      //   icon: 'loading'
      // })
      //改为弹窗购买链接
      wx.showModal({
        title: '提示',
        content: '请购买该资源',
        confirmColor: '#FF4612',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定');
            that.goPay();//购买
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      return false;
    }
    if (that.data.canView && !url) {
      wx.showToast({
        title: '资源地址有误，请确认',
        icon: 'loading'
      })
      return false;
    }
    that.setData({
      curPlayIndex: index,
      // playUrl: url,
      cover:cover,
    })
    that.getNetworkType(function () {
      that.setData({
        playUrl: url,
      })
      that.play();
    });
    console.log('url为' + url)
    // that.play()//调用播放
    //播放统计
    app.addHit(id,'RESOURCE_VIDEO');
  },
  // 判断有无播放权限
  // play(){
  //   console.log(111)
  //   var that=this;
  //   setTimeout(function(){
  //     that.videoContext.pause()
  //      wx.showToast({
  //         title: '请购买',
  //         icon: 'loading',
  //         duration: 2000
  //       })
        
  //   },5000)
   
    
  // },
  // getTime(e){
  //   var that=this;
  //   console.log(e)
  //   if (e.detail.currentTime>=5){
  //     that.videoContext.pause()
  //     that.setData({
  //       isplay:false
  //     })
  //   }
  // },
  // 点击标题切换当前页时改变样式
  swichNav: function (e) {
    var cur = e.currentTarget.dataset.current;
    if (this.data.currentTab == cur) { return false; }
    else {
      this.setData({
        currentTab: cur
      })
    }
  },
  // 是否展示全部内容
  isMoreIntro() {
    if (this.data.isMoreIntro) {
      this.setData({
        isMoreIntro: false
      })
    } else {
      this.setData({
        isMoreIntro: true
      })
    }
  },
  // 查看更多评价
  lookAllComment() {
    console.log(4)
    wx.navigateTo({
      url: '../commentList/commentList',
    })
  },
  // 弹出发表评论弹窗
  showCommentPop() {
    goCommentPop.set('goComment', {
      confirm: function (data) {
        console.log(data)
      }.bind(this)
    });
    goCommentPop.open('goComment')
  },
  // // 购买
  // goPay(e) {
  //   var that = this;
  //   // var courseItem = e.currentTarget.dataset.courseItem;
  //   /////////////
  //   // var coverMain = e.currentTarget.dataset.cover;
  //   // var name = e.currentTarget.dataset.name;
  //   // var currentPrice = e.currentTarget.dataset.price;
  //   // var updateDate = e.currentTarget.dataset.update;
  //   // var chapterCount = e.currentTarget.dataset.chapterCount || 0;//总共集数
  //   // var mediaType = e.currentTarget.dataset.mediaType;//类型
  //   // var id = e.currentTarget.dataset.sourceId;//资源id
  //   //////////
  //   var coverMain = that.data.course.coverMain;
  //   var name = that.data.course.name;
  //   var currentPrice = that.data.course.currentPrice;
  //   var updateDate = that.data.updateDate;
  //   var chapterCount = that.data.chapterCount || 0;//总共集数
  //   var mediaType = that.data.course.mediaType;//类型
  //   var id = that.data.course.id;//资源id
  //   var courseItem = {
  //     coverMain,
  //     name,
  //     currentPrice,
  //     updateDate,
  //     chapterCount,
  //     mediaType,
  //     id
  //   }
  //   courseItem = JSON.stringify(courseItem);
  //   wx.navigateTo({
  //     url: '../pay/pay?courseItem=' + courseItem,
  //   })
  // },
  // 分享
  onShareAppMessage: function (res) {
    var that=this;
    var resourcesItem=that.data.resourcesList[0];
    var url ='' ;//resourcesItem.url
    var id = resourcesItem.id;//课程中资源id
    var courseId = resourcesItem.courseId;//课程id
    var index = 0;//课程序号
    var cover = resourcesItem.cover;//资源封面
    var obj = {
      url,
      id,
      courseId,
      index,
      cover
    }
    // that.setData({
    //   urlObj: obj,
    // })
    // var cover = this.data.course.coverMain || 'http://image.chuangchuang.cn/chuangchuang/cc_other/20171221/20171221_1513820857788.jpg';
    var title = this.data.course.name || '';
    return {
      title: title,
      path: '/pages/videoPlayDetail/videoPlayDetail?urlObj=' + JSON.stringify(obj)+'&isFromShare=true',//是否是分享过来的
      // imageUrl: cover ,//测试
      success: function (res) {
        // 转发成功
        console.log(res)
      },
      fail: function (res) {
        // 转发失败
        console.log(res)
      }
    }
  },
  // 播放进度变化
  timeupdate(e){
    // console.log(e.detail.currentTime);
    var currentTime =e.detail.currentTime;
    var duration = e.detail.duration;
    if ((currentTime - 10) > 0 && (currentTime - 10) < 0.5){
      var curPlayIndex = this.data.curPlayIndex;
      var sourceId = this.data.resourcesList[curPlayIndex].id;
      app.playTimeCount(sourceId, 'RESOURCE_VIDEO', 'PLAY_10S');
      
    } else if ((currentTime - 3 * 60) > 0 && (currentTime - 3 * 60)<0.5){
      var curPlayIndex = this.data.curPlayIndex;
      var sourceId = this.data.resourcesList[curPlayIndex].id;
      app.playTimeCount(sourceId, 'RESOURCE_VIDEO', 'PLAY_3M');
    } else if ((currentTime - duration * 0.85) >= 0 && (currentTime - duration * 0.85) <= 0.5) {
      var curPlayIndex = this.data.curPlayIndex;
      var sourceId = this.data.resourcesList[curPlayIndex].id;
      app.playTimeCount(sourceId, 'RESOURCE_VIDEO', 'PLAY_END');
    }
  },
  // 根据网络类型操作
  getNetworkType(successFun,errorFun){
    var that=this;
    // 获取网络类型
    wx.getNetworkType({
      success: function (res) {
        // 返回网络类型, 有效值：
        // wifi/2g/3g/4g/unknown(Android下不常见的网络类型)/none(无网络)
        var networkType = res.networkType;
        var network4gPlay = wx.getStorageSync('network4gPlay');
        if (networkType == 'wifi' || network4gPlay == 1){
          if (successFun && Object.prototype.toString.call(successFun) === '[object Function]')
            successFun.apply(that);
          return false 
        }
        if (networkType != 'wifi' && network4gPlay != 1) {
          // videoContext.pause();
          wx.showModal({
            title: '正在非wifi网络下播放',
            content: '运营商可能收取网络费用，是否继续学习',
            confirmText: '继续播放',
            confirmColor: '#FF4612',
            success: function (res) {
              if (res.confirm) {
                console.log('用户点击确定');
                if (successFun && Object.prototype.toString.call(successFun) === '[object Function]')
                 successFun.apply(that);
                wx.setStorage({
                  key: 'network4gPlay',
                  data: 1,
                })
                // that.setData({
                //   isPlay: true
                // })
                // videoContext.play();
              } else if (res.cancel) {
                // console.log('用户点击取消');
                if (errorFun && Object.prototype.toString.call(errorFun) === '[object Function]')
                  errorFun.apply(that);
                wx.setStorage({
                  key: 'network4gPlay',
                  data:0,
                })
                // videoContext.pause();
                // return false;
              }

            },

          })
        }
      }
    })
  }

}))
